<?php

namespace Home\Controller;

use Utuo\ForegroundController;

class MicroVoteController extends ForegroundController {
	private $microVote;
	private $microVoteId;
	private $lastRecord;
	public function _init() {
		layout ( false );
		C ( 'TOKEN_ON', false );
		$this->setModelName ();
		$this->microVoteId = I ( 'id', 0, 'intval' ) or $this->ajaxError ( '投票id丢失' );
		$condation = array (
				'cid' => $this->sid,
				'status' => 1,
				'is_deleted' => 0,
				'id' => $this->microVoteId 
		);
		$this->microVote = M ( 'MicroVote' )->where ( $condation )->field ( "*,UNIX_TIMESTAMP(start_time) as start_time,UNIX_TIMESTAMP(end_time) as end_time" )->order ( 'start_time asc' )->find ();
		$this->lastRecord = $this->lastRecord ();
		$this->id = $this->microVote ['id'];
	}
	public function indexAction() {
// 		$this->checkOpenId();
        $this->display ();
	}
	public function getMicroVoteInfoAction() {
		$this->microVote ['itemTitle'] = M ( 'MicroVoteItem' )->where ( 'micro_vote_id=%d  and status=1 and is_deleted=0', $this->microVote ['id'] )->order('sort asc')->field ( 'id,title,pic' )->select ();
	    foreach ( $this->microVote ['itemTitle'] as &$v ) {
			$v ['num'] = M ( 'MicroVoteRecord' )->where ( "selected=".$v['id']." and status=1 and is_deleted=0" )->count ();
		}
	    $this->microVote ['select_options'] = $this->microVote ['select_options'] ? "checkbox" : "radio";
		$this->ajaxReturn ( $this->microVote );
	}
	public function saveRecordAction() {
		//①检查投票是否手动开启
		$this->isopen();
		//②检查当前时间是否在后台设置的时间范围之内
		$this->betweenTime ();
		
		if ($this->canVote ()) {
			$m = D ( 'MicroVoteRecord' );
			$selected = I ( 'selected', 0, 'intval' );
			$m = D ( 'MicroVoteRecord' );
			if ($m->create ()) {
				unset($m->id);
				$m->selected = $selected;
				$m->micro_vote_id=$this->microVoteId;
				$m->open_id = "$this->open_id";
				$m->cid = $this->sid;
				$m->times = $this->getTimes ();
				$m->create_time = time ();
				$m->add () ? $this->ajaxSuccess ( $this->microVote ['result_text'] ) : $this->ajaxError ( '投票失败' .$m->getError());
			}
		}
	}
	private function isopen(){
		$this->microVote['open'] or $this->ajaxError('投票已关闭');
	}
	// 验证微信oped_id合法性
	private function checkOpenId() {
		header("content-type:text/html;charset=utf8");
		$_s = I ( "_s", "" );
		
		if ($_s != \Utuo\Sign::create ( array (
				"open_id" => "$this->open_id",
				"_t" => I ( "_t", "" ) 
		) )) {
			exit( '您必须关注微信公众平台, 才可投票' );
		}
	}
	
	// 获取是否在指定的时间内 betweenTime()
	private function betweenTime() {
		$time = time ();
		if ($time < $this->microVote ['start_time']) {
			$this->ajaxError ( '亲，投票还未开始，再等一会哦！' );
		} elseif ($time > $this->microVote ['end_time']) {
			$this->ajaxError ( '亲，投票已经结束，下次早点来哦！' );
		}
	}
	// 是否可以去投票 canVote
	private function canVote() {
		if ($this->microVote ['time_type'] == 0) {
			return $this->noTimeCanVote ();
		} elseif ($this->microVote ['time_type'] == 1) {
			return $this->timeCanVote ();
		}
	}
	// 不计时时判断是否可以投票noTimeCanVote()
	private function noTimeCanVote() {
		$condation = array (
				'cid' => $this->sid,
				'micro_vote_id' => $this->microVoteId,
				'open_id' => "$this->open_id" 
		);
		$count = M ( 'MicroVoteRecord' )->where ( $condation )->count ();
		if ($count >= $this->microVote ['vote_times']) {
			$this->ajaxError ( '抱歉！只能投' . $this->microVote ['vote_times'] );
		} else {
			return true;
		}
	}
	// 计时判断是否可以投票timeCanVote()
	private function timeCanVote() {
		//获取上一次投票第一个被投票的信息
		$record = $this->lastRecord ();
		
		//①如果该微信号还未投过返回true
		if(empty($record) || is_null($record))
		{
			return true;
		}
		//②获取当前时间距离第一次投票的时间差
		$time = $this->getLeftTime ( $record ['create_time'] );
		//③如果时间差大于后台设置的时间 才可以投票
	   if ($time and $time >= $this->microVote ['minutes'] * 60) { 
		    return true;
		}else{
			//如果时间没超过后台设置的时间，存在两种情况
			$selected = I ( 'selected', 0, 'intval' );
			if ($this->isVoted ( $selected )) {
				$this->ajaxError ( '您已经投过了' );
			} else {
				if ($this->selectedItemsCount () >= $this->microVote ['select_items']) {
					$result=$record['create_time']+$this->microVote['minutes']*60-time();
					$hours=floor($result/3600);
					$minutes=floor(($result-$hours*3600)/60);
					$seconds=($result-$hours*3600)%60;
					$leftTime=$hours."时".$minutes."分".$seconds."秒";
					$this->ajaxError ( '只能对' . $this->microVote ['select_items'] . "名选手进行投票,".$leftTime."后才可以投票" );
				}else{
					return true;
				}
			
			}
		
		}
	}
	// 获得上次投票信息
	private function lastRecord() {
		$condation = array (
				'cid' => $this->sid,
				'micro_vote_id' => $this->microVoteId,
				'open_id' => "$this->open_id",
				'status'=>1,
				'is_deleted'=>0 
		);
		$record = M ( 'MicroVoteRecord' )->where ( $condation )->order ( 'times desc ,create_time asc' )->find ();
		
		if ($record === false) {
			$this->ajaxError ( '亲~网络有点忙，请再试一次吧！' );
		} else {
			return $record;
		}
	}
	private function getLeftTime($t) {
		$time = time () - $t;
	
		return $time;
	}
	// 获取第几次投票
	private function getTimes() {
		$time = $this->getLeftTime ( $this->lastRecord ['create_time'] );
	
		if (empty ( $this->lastRecord ) || is_null($this->lastRecord)) {
		   return	$order = 1;
		}
		if ($time and $time >= $this->microVote ['minutes'] * 60) {
			$order = $this->lastRecord ['times']+1;
		} else {
			$order = $this->lastRecord ['times'];
		}
		return $order;
	}
	// 判断该次投票是否已经对该选项已经投过票
	private function isVoted($itemId) {
		$itemId or $this->ajaxError ( '亲~网络有点忙，请再试一次吧！' );
		$condation = array (
				'cid' => $this->sid,
				'micro_vote_id' => $this->microVoteId,
				'times' => $this->lastRecord ['times'],
				'open_id'=>"$this->open_id",
				'selected' => $itemId 
		);
		$count = M ( 'MicroVoteRecord' )->where ( $condation )->count ();
	    $count===false and $this->ajaxError('亲~网络有点忙，请再试一次吧！');
		return $count > 0;
	}
	
	// 记录该微信号投票选项个数
	private function selectedItemsCount($selected) {
		$condation = array (
				'cid' => $this->sid,
				'micro_vote_id' => $this->microVoteId,
				'open_id'=>"$this->open_id",
				'times' => $this->lastRecord ['times'] 
		);
		$count = M ( 'MicroVoteRecord' )->where ( $condation )->count ();
		
		$count === false and $this->ajaxError ( '亲~网络有点忙，请再试一次吧！' );
		return $count;
	}
	
	// 获取排行榜
	public function rankingListAction() {
		$condation = array (
				'm.status' => 1,
				'm.is_deleted' => 0,
				'r.status' => 1,
				'r.is_deleted' => 0,
				'm.cid' => $this->sid,
				'r.micro_vote_id ' => $this->microVote ['id'],
				'm.micro_vote_id ' => $this->microVote ['id'] 
		);
		$m = M ( 'MicroVoteItem m' );
		$rankingList = $m->join ( "__MICRO_VOTE_RECORD__ r on m.id=r.selected" )->where ( $condation )->field ( 'm.id,count(m.id) as num,m.title' )->group ( 'm.id,m.title' )->order ( 'num desc' )->select ();
		$i = 1;
		foreach ( $rankingList as $key => &$v ) {
			if ($key == 0) {
				$v ['sort'] = 1;
			} elseif ($rankingList [$key] ['num'] == $rankingList [$key - 1] ['num']) {
				$rankingList [$key] ['sort'] = $rankingList [$key - 1] ['sort'];
			} else {
				$i ++;
				$v ['sort'] = $i;
			}
		}
		$this->ajaxReturn ( $rankingList );
	}
}